
import { Icon } from "@/components";
import { useVisible } from "@/tools/hooks";
import { server } from "@/views/Development/server";
import { Button, ButtonProps, Drawer, Form, FormInstance, Input } from "antd";
import React from "react";

/** 图标选择器 */
export function IconSelect(props: ButtonProps & { value?: string, onChange?: (value: string) => void }) {

    const [value, setValue] = React.useState<string | undefined>(props.value);

    const { open, onClose, onOpen } = useVisible()

    const [iconList, setIconList] = React.useState<string[]>([])

    const { addIconDrawer } = useAddIconDrawer();

    /** 添加图标 */
    const addIcon = React.useCallback(async () => {
        try {
            const iconId = await addIconDrawer.start();
            setValue(iconId);
            props.onChange && props.onChange(iconId)
            onClose()
        } catch (error) {
            console.error(error);
        }
    }, [addIconDrawer, onClose, props])

    // 获取图标数据
    React.useEffect(() => {
        if (!open) return;
        server('/dev/icons/get')
            .then(e => e?.json())
            .then(async e => {
                setIconList(e);
            }).catch(() => {
                setIconList([])
            })
    }, [open])

    return (
        <>
            <Button onClick={onOpen} {...props} icon={<Icon id={value} />} />
            <Drawer
                title="选择图标"
                onClose={onClose}
                open={open}
                footer={
                    <Button block onClick={addIcon} >添加图标</Button>
                }
            >
                {addIconDrawer.element}
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {iconList.map(e => (
                        <Button
                            icon={<Icon id={e} />}
                            onClick={() => {
                                setValue(e);
                                props.onChange && props.onChange(e)
                                onClose()
                            }}
                        />
                    ))}
                </div>
            </Drawer>
        </>
    )
}

/** 添加图标窗口 */
function useAddIconDrawer() {

    const [promise, setPromise] = React.useState<{ resolve: (value: string | PromiseLike<string>) => void, reject: (reason?: any) => void }>()

    const formRef = React.useRef<FormInstance>(null);

    /** 
     * 开始添加图标 
     * @returns 图标ID
     * */
    const start = React.useCallback(() => new Promise<string>((resolve, reject) => {
        setPromise({ resolve, reject })
    }), [])

    const onClose = React.useCallback(() => {
        promise?.reject(new Error('取消添加图标'));
        setPromise(undefined)
    }, [promise])

    const onFinish = React.useCallback(async ({ code }) => {
        await server('/dev/icons/add', {
            method: 'POST',
            body: code,
        })
        onClose()
    }, [onClose])

    /** 添加图标窗口-结构 */
    const element = React.useMemo(() => {
        return (
            <Drawer
                title="添加图标"
                onClose={onClose}
                open={!!promise}
            >
                <Form ref={formRef} onFinish={onFinish} >
                    <Form.Item
                        name="code"
                        rules={[
                            { required: true, message: '请输入SVG源码' }
                        ]}
                    >
                        <Input.TextArea placeholder="粘贴SVG源码" rows={5} />
                    </Form.Item>

                    <Button htmlType='submit' block >添加</Button>
                </Form>
            </Drawer>
        )
    }, [onClose, onFinish, promise])

    React.useEffect(() => { !!promise && formRef.current?.resetFields() }, [promise])

    return {
        /** 添加图标窗口 */
        addIconDrawer: {

            /** 
             * 开始添加图标 
             * @returns 图标ID
             * */
            start,

            /** 添加图标窗口-结构 */
            element,
        }
    }
}

